package com.wang.web3;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wang.web3.base.Constant;
import com.wang.web3.bean.TianWallet;
import com.wang.web3.bean.TianWallets;
import com.wang.web3.utils.SPUtils;

import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.web3j.crypto.CipherException;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;
import org.web3j.crypto.WalletUtils;
import org.web3j.utils.Numeric;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.bitcoinj.crypto.HDUtils.parsePath;

public class IntoWordsFragment extends Fragment implements View.OnClickListener{
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public IntoWordsFragment() {
        // Required empty public constructor
    }

    EditText tvWords,walletPwd1,walletPwd2,name;
    Button mBtnInto;

    public static IntoWordsFragment newInstance() {
        IntoWordsFragment fragment = new IntoWordsFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_into_words, container, false);
        tvWords = view.findViewById(R.id.tvWords);
        walletPwd1 = view.findViewById(R.id.walletPwd1);
        walletPwd2 = view.findViewById(R.id.walletPwd2);
        mBtnInto = view.findViewById(R.id.mBtnInto);
        name = view.findViewById(R.id.name);
        mBtnInto.setOnClickListener(this);
        return view;
    }

    private TianWallet createETHWalletFromWords(String words){
        List<String> list =  Arrays.asList(words.split("\\s+"));
        DeterministicSeed deterministicSeed = new DeterministicSeed(list, null, "", 0);
        DeterministicKeyChain deterministicKeyChain = DeterministicKeyChain.builder().seed(deterministicSeed).build();
        String DERIVATION_PATH = "M/44H/60H/0H/0/0";
        DeterministicKey deterministicKey = deterministicKeyChain.getKeyByPath(parsePath(DERIVATION_PATH), true);

        BigInteger privateKey = deterministicKey.getPrivKey();
        ECKeyPair ecKeyPair = ECKeyPair.create(privateKey);


        try {
            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + Constant.WalletUri;
            String fileName =  WalletUtils.generateWalletFile(walletPwd1.getText().toString(),ecKeyPair,new File(filePath),false);

        } catch (CipherException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String address = Keys.getAddress(ecKeyPair);

        TianWallet tianWallet = new TianWallet(name.getText().toString(),"0x" + address, Numeric.toHexStringWithPrefix(ecKeyPair.getPrivateKey()), Numeric.toHexStringWithPrefix(ecKeyPair.getPublicKey()), words);

        Gson gson = new Gson();
        //读出原有的
        String ss = (String) SPUtils.get(getActivity(),Constant.WalletKey,"");
        TianWallets wallets;
        if (!ss.equals("")){
            wallets = gson.fromJson(ss, TianWallets.class);
        }else {
            wallets = new TianWallets(new ArrayList<TianWallet>());
        }

        wallets.getTianWallets().add(tianWallet);
        SPUtils.put(getActivity(), Constant.WalletKey,gson.toJson(wallets));


        Toast.makeText(getActivity(),"导入成功",Toast.LENGTH_SHORT).show();
        getActivity().setResult(1,new Intent());
        getActivity().finish();

        return tianWallet;
    }

    @Override
    public void onClick(View v) {
        String na = name.getText().toString();
        String pwd1 = walletPwd1.getText().toString();
        String pwd2 = walletPwd2.getText().toString();
        String words = tvWords.getText().toString();
        if (na.equals("") || pwd1.equals("") || pwd2.equals("") || words.equals("")){
            Toast.makeText(getActivity(),"以上信息必填",Toast.LENGTH_SHORT).show();
            return;
        }
        if (!pwd1.equals(pwd2)){
            Toast.makeText(getActivity(),"两次密码不一致",Toast.LENGTH_SHORT).show();
            return;
        }
        createETHWalletFromWords(words);
    }
}
